package me.everything.webp;


import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.nio.ByteBuffer;

public class WebPDecoder {
    private static WebPDecoder instance = null;

    private WebPDecoder() {
        System.loadLibrary("webp_evme");
    }

    public static WebPDecoder getInstance() {
        if (instance == null) {
            synchronized (WebPDecoder.class) {
                if (instance == null) {
                    instance = new WebPDecoder();
                }
            }
        }
        return instance;
    }

    public PixelMap decodeWebP(byte[] encoded) {
        return decodeWebP(encoded, 0, 0);
    }

    public PixelMap decodeWebP(byte[] encoded, int w, int h) {
        int[] width = new int[]{w};
        int[] height = new int[]{h};
        byte[] decoded = decodeRGBAnative(encoded, encoded.length, width, height);
        if (decoded.length == 0) return null;
        int[] pixels = new int[decoded.length / 4];
        ByteBuffer.wrap(decoded).asIntBuffer().get(pixels);
        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.pixelFormat = PixelFormat.ARGB_8888;
        options.size = new Size(width[0],height[0]);
        return PixelMap.create(pixels,options);
    }

    public static native byte[] decodeRGBAnative(byte[] encoded, long encodedLength, int[] width, int[] height);
}
